<template>
  <page-header-wrapper>
    <div>
      <a-row :gutter="24">
        <a-col span="24">
          <div style="margin-bottom: 16px">
            <a-button type="primary" :disabled="!hasSelected" :loading="loading" @click="start">
              批量设置
            </a-button>
            <a-button type="primary" @click="bye" style="margin-left:10px">
              轮空值设置
            </a-button>
            <label style="margin-left:30px">年度:</label>
            <a-range-picker @change="onChangeday" style="margin:5px" :format="dateFormat" />
            <a-input-search placeholder="输入您要搜索的内容" enter-button @search="onSearch" style="width:17%;margin-left:10px;margin-top:5px" v-model="search" />
            <span style="margin-left: 8px">
              <template v-if="hasSelected">
                {{ `Selected ${selectedRowKeys.length} items` }}
              </template>
            </span>
          </div>
          <keep-alive>
            <a-table
              :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
              :columns="columns"
              :data-source="datarevamp"
              @change="handleTableChange"
              :loading="tableLoading"
              :pagination="pagination"
            >
              <span slot="classic_name" slot-scope="classic_name">
                <a-tag color="cyan">
                  {{ classic_name }}
                </a-tag>
              </span>
              <span slot="status" slot-scope="status">
                <a-tag color="green">
                  {{ status }}
                </a-tag>
              </span>
              <template slot="action" slot-scope="text, record">
                <a @click="handleInfo(record)">详情</a>
              </template>
            </a-table>
          </keep-alive>
        </a-col>
      </a-row>
      <a-modal
        title="轮空值设置"
        v-model="byebye"
        :closable="closable"
        ok-text="确认"
        @ok="hideModal"
      >
        <a-form-model :label-col="{span:6}" :wrapper-col="{span: 17}" >
          <p style="color: red;">注意:修改的是协会的轮空值，而非论证报告的轮空值</p>
          <a-form-model-item label="轮空值设定" style="margin-left:120px">
            <a-input-number v-model="bye_name" :min="0" :precision="0"/>
          </a-form-model-item>
        </a-form-model>
      </a-modal>
      <a-card v-show="!disvisible">
        <a-modal
          :visible="extractvisible"
          v-if="extractvisible"
          @cancel="handleExtractClose()"
          @ok="handleExtractOk()"
          title="规则构建"
          :confirm-loading="extractLoading"
          okText="确定"
          cancelText="取消"
          width="52%"
        >
          <a-form-model
            ref="extractionrules"
            :label-col="{span: 8}"
            :wrapper-col="{span: 16}"
            :model="extractionrules"
          >
            <a-form-model-item
              v-for="(item, index) in extractionrules.extract_rules"
              :key="index"
              :label="item.rule_name"
              :prop="'extract_rules.' + index + '.rule_value'"
            >
              <a-input-number
                style="margin-left:15px; width:90px"
                v-model="item.rule_value"
                :min="0"
                :precision="0"/>
              <!-- <a-switch checked-children="必传" un-checked-children="非必传" default-checked style="margin-left:15px"/> -->
              <a-switch checked-children="开启权限" un-checked-children="关闭权限" v-model="item.is_open" style="margin-left:15px"/>
            </a-form-model-item>
          </a-form-model>
        </a-modal>
      </a-card>
    </div>
  </page-header-wrapper>
</template>

<script>
import { ruletable, rulechange, rulechangeok, byevalue, byechange, fuzzysearch, mostamend } from '@/api/rule'
const delay = (function () {
 let timer = 0
 return function (callback, ms) {
  clearTimeout(timer)
  timer = setTimeout(callback, ms)
 }
})()
export default {
  data () {
    return {
      bye_name: '',
      dateFormat: 'YYYY/MM/DD',
      extractionrules: {},
      extractLoading: false,
      extractvisible: false,
      disvisible: true,
      search: '',
      tableLoading: false,
      datarevamp: [],
      selectedRowKeys: [], // Check here to configure the default column
      loading: false,
      closable: false,
      byebye: false,
      pagination: {
        current: 1,
        pageSize: 12,
        total: 0,
        showSizeChanger: true,
        pageSizeOptions: ['12', '20', '30', '50']
      },
      columns: [
        {
          title: '危大类别',
          dataIndex: 'classic_name',
          key: 'classic_name',
          scopedSlots: { customRender: 'classic_name' },
          width: '10%'
        },
       {
          title: '序号',
          dataIndex: 'index',
          key: 'index',
          align: 'center',
          width: 70,
          customRender: (text, record, index) => `${(this.pagination.current - 1) * this.pagination.pageSize + index + 1}`
        },
        {
          title: '论证编号',
          dataIndex: 'argument_num'
          // sorter: true,
          // needTotal: true,
          // customRender: (text) => text + ' 次'
        },
        {
          title: '工程名称',
          dataIndex: 'project_name'
        },
        {
          title: '委托日期',
          dataIndex: 'entrust_time'
        },
        // {
        //   title: '论证日期',
        //   dataIndex: 'create_time'
        // },
        {
          title: '论证状态',
          dataIndex: 'status',
          key: 'status',
          scopedSlots: { customRender: 'status' }
        },
        // {
        //   title: '联系方式',
        //   dataIndex: 'phone'
        // },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          width: 240,
          fixed: 'right',
          scopedSlots: { customRender: 'action' }
        }
      ],
      rules: {
      }
    }
  },
  computed: {
    hasSelected () {
      return this.selectedRowKeys.length > 0
    }
  },
  watch: {
    search: function (newVal, oldVal) {
      delay(() => {
        this.onSearch(newVal)
      }, 1000)
    }
  },
  mounted () {
  },
  methods: {
    start () {
      this.invincible = 1
      this.loading = true
      this.disvisible = false
      this.extractvisible = true
      mostamend().then(res => {
        this.extractionrules = res.result
        this.loading = false
      })
    },
    onSelectChange (selectedRowKeys, record) {
      console.log(selectedRowKeys)
      this.fff = record
      console.log(record)
      this.selectedRowKeys = selectedRowKeys
      var timeArr = []
      for (let i = 0; i < record.length; i++) {
        timeArr[i] = record[i].argument_id
      }
      this.batch = timeArr
      console.log(this.batch)
    },
    bye () {
      console.log(123)
      this.byebye = true
      byevalue().then(res => {
        this.byevalue_name = JSON.parse(JSON.stringify(res.result))
        this.bye_name = res.result.rule_value
        this.bye_id = res.result.rule_id
        console.log(this.bye_name)
      })
    },
    hideModal () {
      console.log(159)
      var changebye = new FormData()
      changebye.append('rule_id', this.bye_id)
      changebye.append('rule_value', this.bye_name)
      byechange(changebye).then(res => {
        console.log(res)
        this.byebye = false
        this.$message.success('轮空值修改成功')
      })
    },
    onChangeday (date, dateString) {
      this.datestring = dateString
      this.onSearch()
    },
    getTableData (query) {
      // console.log(query)
      this.tableLoading = true
      var fd = new FormData()
      fd.append('per_page', this.pagination.pageSize)
      fd.append('current_page', this.pagination.current)
      if (query) {
        fd.append('query', query)
      }
      console.log(fd)
      ruletable(fd).then(res => {
        this.datarevamp = res.result.data
        Object.assign(this.pagination, { 'pageSize': Number(res.result.per_page), 'total': res.result.total, 'current': res.result.current_page })
        console.log(this.datarevamp)
        this.tableLoading = false
      })
      .catch(err => {
        this.$notification['error']({
          message: 'Error',
          description: err.message
        })
      })
    },
    handleExtractOk () {
          if (this.invincible === 2) {
          // eslint-disable-next-line no-unused-expressions
          this.$refs['extractionrules']
          console.log(this.extractionrules.extract_rules)
          var b = {
            'argument_id': this.perform,
            'extract_rules': this.extractionrules.extract_rules
          }
          rulechangeok(b).then(res => {
            // this.extractStatus = res.result[0]
            this.extractLoading = true
            this.extractLoading = false
            this.extractvisible = false
            this.$message.success('论证规则修改成功')
          })
        } else if (this.invincible === 1) {
          // eslint-disable-next-line no-unused-expressions
          this.$refs['extractionrules']
          console.log(this.extractionrules)
          var a = {
            'argument_id': this.batch,
            'extract_rules': this.extractionrules.extract_rules
          }
          rulechangeok(a).then(res => {
            // this.extractStatus = res.result[0]
            this.extractLoading = true
            this.extractLoading = false
            this.extractvisible = false
            this.selectedRowKeys = []
            this.$message.success('论证规则修改成功')
          })
        }
    },
    handleInfo (record) {
      // this.showData = JSON.parse(JSON.stringify(record)) // 深拷贝，防止表格数据被影响
      // console.log(this.showData)
      this.invincible = 2
      var ggbb = [record.argument_id]
      console.log(ggbb)
      this.perform = ggbb
      console.log(this.perform)
      this.disvisible = false
      this.extractvisible = true
      var argumentmessid = new FormData()
      argumentmessid.append('argument_id', record.argument_id)
      rulechange(argumentmessid).then(res => {
        Object.assign(res.result, { 'argument_id': Number(record.argument_id) })
        this.extractionrules = res.result
      })
      // this.visible = true
    },
    handleExtractClose () {
      this.extractvisible = false
      this.selectedRowKeys = []
    },
    handleTableChange (pagination) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      // this.getTableData(this.search)
      if (this.search) {
        this.onSearch()
      } else {
        this.getTableData()
      }
    },
    onSearch (value) {
      console.log(value)
      var query = new FormData()
      query.append('query', this.search)
      if (this.datestring[0]) {
        query.append('start_date', (new Date(this.datestring[0])).getTime() / 1000)
        query.append('end_date', (new Date(this.datestring[1])).getTime() / 1000)
      }
      this.loading = true
      fuzzysearch(query).then(res => {
        this.datarevamp = res.result.data
        Object.assign(this.pagination, { 'pageSize': Number(res.result.per_page), 'last_page': res.result.last_page, 'current': res.result.current_page })
        this.loading = false
      })
    }
  },
  created () {
    this.getTableData()
  }
}
</script>

<style lang="less" scoped>

</style>
